import React, { useEffect, useState } from "react";
import ContentCard from "../../../components/ContentCard";
import Button from "@knownsec/react-component/dist/Button";
import Message from "@knownsec/react-component/dist/Message";
import Input from "@knownsec/react-component/dist/Input";
import Icon from "@knownsec/react-component/dist/Icon";
import Table from "@knownsec/react-component/dist/Table";
import Confirm from "@knownsec/react-component/dist/Confirm";
import Dialog from "@knownsec/react-component/dist/Dialog";
import Pagination from "@knownsec/react-component/dist/Pagination";
import CopyBoard from "../../../components/CopyBoard";
import Textarea from '../../../components/Textarea';
import { datetime } from '../../../../common/formatter';
import { turnToUrlparam } from "../../../helpers/getUrlParams";
import EmptyData from "../../../components/empty/EmptyData";
import fetchFer from 'API/fetch';
import cn from 'classnames'
import s from './style.module.css'

function ChangeCheckPages () {
  const [data, setData] = useState([])
	const [targetName, setTargetName] = useState('')
	const [targetUrl, setTargetUrl] = useState('')
	const [total, setTotal] = useState(1)
  const [urlDetail,setUrlDetail] = useState([])
	const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [filter, setFilter] = useState({
		page: 1,
		limit: 10,
		target_name: '',
    target_url:''
	})

	const columns = [
		{
			title: '资产名称',
			dataIndex: 'target_name',
			render (target_name) {
				return <CopyBoard text={target_name} className={s.db} maxWidth='6rem' />
			}
		},
		{
			title: '资产地址',
			dataIndex: 'target_url',
      render (target_url) {
				return <CopyBoard text={target_url} className={s.db} maxWidth='11rem' />
			}
		},
    {
      title: '样本页面数',
      dataIndex: 'page_count',
      render(page_count, {urls}) {
        return <Button type='text' className={s.p0} onClick={() => {
          setVisible(true)
          setUrlDetail([...urls])
        }}>{page_count}</Button>
      }
    },
		{
			title: '上次更新时间',
			dataIndex: 'updated_at',
      render: e => {
        return datetime(e) || '- -';
      },
		},
		{
			title: '操作',
			dataIndex: 'task_id',
			width: 140,
			render (task_id, { status }) {
				return <Button disabled={status === "waiting"} type='text' className={s.p0} onClick={() =>  showUpdateConfirm([task_id])}>{status === "waiting" ? "更新中" : "更新"}</Button>
			}
		}
	]

	const getChangeCheckList = async () => {
		setLoading(true)
		setData([])
		const params = turnToUrlparam(filter)
		const res = await fetchFer(`/api/v2/base_page/list?${params}`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});

		if (res.code === 200) {
			const resData = res.data.result.map((item, k) => {
				item.key = item.task_id
				return item
			})
			setData(resData)
			setTotal(res.data.count)
		}
		setLoading(false)
	}

  const updateDemoPage = async (ids) => {
    const res = await fetchFer(`/api/v2/base_page/update`, {
      method: 'POST',
      body: JSON.stringify({ task_ids: ids }),
      checkStatus: 501,
    }).catch(err => err);
    res.code === 200
      ? Message.show({ type: 'success', message: res?.message })
      : Message.show({ type: 'error', message: '操作失败' })
  }

  const showUpdateConfirm = (task_id) => {
    const template =(
      <div className={cn('mb10 pt0 pb0 pl20 pr20')}>
        <Icon type='error' className={cn('warning-color fs24 mb10 db tac')} />
        <div className="tac">系统将以该页面最新爬取信息作为监测样本,您确定要更新吗?</div>
        <div className="tac">更新后的样本将在下一周期生效</div>
      </div>
    )

    Confirm({
      pro: true,
      className: s.w350,
      message: template,
      onconfirm: ()=> updateDemoPage(task_id),
      oncancel: () => { }
    })
  }

  const DemoPageDetail = () =>
    <Dialog
      visible={visible}
      destroyOnClose={true}
      className={s.w540}
      title={`样本页面详情`}
      onsubmit={() => setVisible(false)}
      onhide={() => setVisible(false)}
      maskStyle={{ zIndex: 100 }}
    >
      <Textarea
        disabled
        style={{width:450}}
        className={cn(s.textarea, s.defaultLibrary)}
        placeholder="样本页面详情"
        rows="8"
        value={urlDetail.join("\n")}
      />
    </Dialog>

	useEffect(() => {
		getChangeCheckList()
	}, [filter])
	return <ContentCard bread={{
		arr: [
			{ link: "", name: "综合管理" },
			{ link: "", name: "篡改策略", active: true},
		],
	}} content={<div className="p20">
		<div className="df aic jcsb">
			<Input
      placeholder='搜索资产名称'
      value={targetName}
      onChange={({ value }) => setTargetName(value.trim()) }
      onSearch={({ value }) => setFilter({...filter, page: 1, target_name: value.trim() })}
      search
      className={s.w240}
      />
      <Input
      placeholder='搜索资产地址'
      value={targetUrl}
      onChange={({ value }) => setTargetUrl(value.trim()) }
      onSearch={({ value }) => setFilter({...filter, page: 1, target_url: value.trim() })}
      search
      className={s.w240}
      />
		</div>
		<Table
			pro
			loading={loading}
			className={cn(s.smallTable, 'mt16')}
			columns={columns}
			empty={<EmptyData borderless={true} />}
			rowSelection={{
				width: 50,
				selectedRowKeys,
				onChange:(newSelectedRowKeys) => {
          setSelectedRowKeys(newSelectedRowKeys);
        },
				getCheckboxProps: (record) => ({
					disabled: !record.key
				})
			}}
			data={data} />
		<div className="df aic jcsb mt10">
			<Button className={s.p0} onClick={() => showUpdateConfirm(selectedRowKeys)} type='text' disabled={selectedRowKeys.length === 0}>批量更新</Button>
			{total > 10 && <Pagination
				current={filter?.page}
				pageSize={filter?.limit}
				showQuickJumper={{ goButton: true }}
				showSizeChanger={true}
				showTotal={total => `共${total}条`}
				pageSizeOptions={['10', '20', '50']}
				total={total}
				onChange={(page, limit) => setFilter({...filter, page, limit})}
			/>}
		</div>
    <DemoPageDetail />
	</div>} />
}

export default ChangeCheckPages
